#include "BlockQueue.hpp"
#include "Task.hpp"

const std::string oper = "+-*/%";

int my_math(int x, int y, char op)
{
    int result = 0;
    switch (op)
    {
    case '+':
        result = x + y;
        break;
    case '-':
        result = x - y;
        break;
    case '*':
        result = x * y;
        break;
    case '/':
    {
        if (y == 0)
        {
            std::cerr << "div zero" << std::endl;
            return -1;
        }
        else
        {
            result = x / y;
        }
        break;
    }
    case '%':
        if (y == 0)
        {
            std::cerr << "moved zero" << std::endl;
            return -1;
        }
        else
        {
            result = x % y;
        }
        break;
    default:
        break;
    }
    return result;
}

void *producer(void *args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        // 生产者进行生产
        int x = rand() % 10 + 1;
        int y = rand() % 5;
        int opercode = rand() % oper.size();
        Task t(x, y, oper[opercode], my_math);
        bq->push(t);
        std::cout << "生产任务 " << t.toString() << std::endl;
        sleep(1);
    }
    return nullptr;
}

void *consumer(void *args)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    while (true)
    {
        // 消费者进行消费
        Task t;
        bq->pop(&t);
        std::cout << "消费任务 " << t() << std::endl;
    }
    return nullptr;
}

int main()
{
    srand((unsigned int)time(0) ^ getpid());
    BlockQueue<Task> *bq = new BlockQueue<Task>;
    pthread_t p, c; // 生产者，消费者线程,通过创建线程的第四个参数看到同一个BQ
    pthread_create(&c, nullptr, consumer, (void *)bq);
    pthread_create(&p, nullptr, producer, (void *)bq);

    pthread_join(c, nullptr);
    pthread_join(p, nullptr);
    delete bq;
    bq = nullptr;
    return 0;
}